﻿using RPCServer.Attributes;
using RPCServer.Core;
using RPCServer.Struct;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace RPCServer.Protocol
{
    [MObject]
    [Protocol(1, Tag = "RPC命令")]
    class RPCCommand
    {
        const char SplitTag = ' ';

        public bool isSuccess = false;
        public int cmdType;
        public string[] args;

        public static MBuffer Encode(object rpcmd)
        {
            RPCCommand cmd = rpcmd as RPCCommand;
            MBuffer buffer = MObjectManager.Instance.GetItem<MBuffer>();
            buffer.WriteInt32(cmd.cmdType);
            StringBuilder sb = new();
            foreach (var arg in cmd.args)
            {
                sb.Append($"{arg} ");
            }
            buffer.WriteString(sb.ToString());
            return buffer;
        }

        public static object Decode(MBuffer data)
        {
            RPCCommand cmd = MObjectManager.Instance.GetItem<RPCCommand>();
            if(data.TryReadInt32(out cmd.cmdType) && data.TryReadString(out string str))
            {
                cmd.args = str.Trim().Split(SplitTag);
                cmd.isSuccess = true;
            }
            MObjectManager.Instance.RecycleItem(data);
            return cmd;
        }
    }
}
